package zmee.pur.src.opplugin;

import kd.bos.dataentity.entity.DynamicObject;
import kd.bos.dataentity.entity.DynamicObjectCollection;
import kd.bos.entity.plugin.AbstractOperationServicePlugIn;
import kd.bos.entity.plugin.args.AfterOperationArgs;
import kd.bos.orm.query.QFilter;
import kd.bos.servicehelper.BusinessDataServiceHelper;
import kd.bos.servicehelper.QueryServiceHelper;
import kd.bos.servicehelper.operation.SaveServiceHelper;

import java.util.Set;
import java.util.stream.Collectors;

/**
 * @Author: xw
 * @Date: 2022/11/22/10:46
 * @Description: 审核时将中标供应商数量反写回中标原则【中标供应商数量】
 */
public class DecisionAuditOp extends AbstractOperationServicePlugIn {

    /**
     * 报表分析
     */
    public static final String KEY_SRC_ANALYSETOOL = "src_analysetool";

    /**
     * 中标原则
     */
    public static final String KEY_SRC_PROJECT_RULE = "src_project_rule";

    @Override
    public void afterExecuteOperationTransaction(AfterOperationArgs e) {
        super.afterExecuteOperationTransaction(e);
        DynamicObject[] dataEntities = e.getDataEntities();
        DynamicObject entity = dataEntities[0];
        //寻源项目编号
        String billNo = entity.getString("billno");
        QFilter filter = new QFilter("project.billno", "=", billNo);
        filter.and("entrystatus", "in", new String[]{"C", "D"}).and("result", "=", "1");
        //查询议价单中标的
        DynamicObjectCollection analyseTool = QueryServiceHelper.query(KEY_SRC_ANALYSETOOL, "id,supplier", filter.toArray());
        if (!analyseTool.isEmpty()) {
            Set<Long> supplier = analyseTool.stream().map(a -> a.getLong("supplier")).collect(Collectors.toSet());
            //中标供应商数量
            int size = supplier.size();

            String parentId = entity.getString("parentid");
            QFilter filter1 = new QFilter("parentid", "=", parentId);
            DynamicObject rule = BusinessDataServiceHelper.loadSingle(KEY_SRC_PROJECT_RULE, "id,winerqty", filter1.toArray());
            rule.set("winerqty", size);
            SaveServiceHelper.save(new DynamicObject[]{rule});
        }
    }
}
